﻿using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Cart.Models;
using Web.Base.Models;
using Web.Base.Security;
using Web.Base.ActionFilters;
using System.Threading.Tasks;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extensions;
using Ayatta.Contract.Component;

namespace Web.Cart.Controllers
{
    [SkAuthorize(UserRole.Buyer)]
    public class CheckoutController : CartBaseController
    {
        public CheckoutController(ILogService logService, IBaseService baseService, IExtraService extraService, IStoreService storeService, IOrderService orderService, IGameService gameService, IAuctionService auctionService, IPassportService passportService, IPaymentService paymentService, IMemcachedClient memcachedClient)
            : base(logService, baseService, extraService, storeService, orderService, gameService, auctionService, passportService, paymentService, memcachedClient)
        {
        }

        public ActionResult Index(byte? param, ShoppingCart cart)
        {
            var userId = User.Identity.Identity().Id;
            var model = new CheckoutControllerModel.Index();
            if (cart.UserAddress == null)
            {
                model.Param = 0;
                var addresses = GetUserAddresses(userId);
                var address = addresses.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                if (address != null)
                {
                    if (address.Province.IsNullOrEmpty() || address.City.IsNullOrEmpty() || address.District.IsNullOrEmpty())
                    {
                        var areas = GetAreaNames(address.AreaId, GetAreas());
                        address.Province = areas.Item1;
                        address.City = areas.Item2;
                        address.District = areas.Item3;
                    }
                    cart.UserAddress = address;
                }
            }
            if (param.HasValue && param.Value == 1)
            {
                model.Param = 1;
                var addresses = PassportService.GetUserAddresses(userId);
                model.UserAddresses = addresses;
            }
            if (ShoppingCart.Config.InvoiceEnabled)
            {
                if (cart.UserInvoice == null)
                {
                    model.Param = 2;
                    var invoices = PassportService.GetUserInvoices(userId);
                    var invoice = invoices.OrderByDescending(o => o.IsDefault).FirstOrDefault();
                    cart.UserInvoice = invoice;
                }
                if (param.HasValue && param.Value == 3)
                {
                    model.Param = 3;
                    var invoices = PassportService.GetUserInvoices(userId);
                    model.UserInvoices = invoices;
                }
            }
            cart.ShippingCharge = 10;
            model.ShoppingCart = cart;
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(byte? param, ShoppingCart cart, UserAddress userAddress, UserInvoice userInvoice)
        {
            var identity = User.Identity.Identity();

            var result = new SkResult<string>();
            if (param.HasValue && param.Value.IsIn(new byte[] { 0, 1 }) && userAddress != null)
            {
                userAddress.UserId = identity.Id;
                userAddress.CountryId = 86;
                userAddress.CreatedBy = User.Identity.Name;
                userAddress.Category = AddressCategory.Receive;
                var areas = GetAreaNames(userAddress.AreaId, GetAreas());
                userAddress.Province = areas.Item1;
                userAddress.City = areas.Item2;
                userAddress.District = areas.Item3;

                cart.UserAddress = userAddress;

                result.Status = true;
                return Json(result);
            }
            if (param.HasValue && param.Value.IsIn(new byte[] { 2, 3 }) && ShoppingCart.Config.InvoiceEnabled &&
                userInvoice != null)
            {
                userInvoice.UserId = identity.Id;

                userInvoice.CreatedBy = User.Identity.Name;

                cart.UserInvoice = userInvoice;

                result.Status = true;
                return Json(result);
            }
            if (cart.UserAddress != null && cart.Items.Count > 0)
            {
                var order = cart.ToOrder(GetIpAddress());
                var status = OrderService.CreateOrder(order);
                if (status)
                {
                    //Task.Factory.StartNew(() => CreateTrade(order.Id));

                    result.Status = true;
                    result.Data = order.Id;
                    Session[ShoppingCart.SessionKey] = null;
                }
                else
                {
                    result.Message = "生成订单失败！";
                }
            }
            return Json(result);
        }

    }
}
